package com.songyuesheng.app.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.songyuesheng.app.commom.ContextHolder;
import com.songyuesheng.app.commom.Result;
import com.songyuesheng.app.entity.History;
import com.songyuesheng.app.mapper.HistoryMapper;
import com.songyuesheng.app.service.OssUploaderService;
import com.songyuesheng.app.vo.DetectVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author song
 * @Date 2025/4/19 18:34
 */
@Slf4j
@RestController
public class DetectController {

    @Value("${ai-service.strawberry-detect}")
    private String aiServiceURL;

    @Autowired
    private OssUploaderService ossUploaderService;

    @Autowired
    private HistoryMapper historyMapper;

    @Value("${oss.detect-directory}")
    private String detectDirectory;

    @PostMapping("/detect")
    public Result<?> detect(@RequestBody String originImage, HttpServletRequest request) throws JsonProcessingException {
        //开始计时
        long s1 = System.currentTimeMillis();
        log.info("本次AI请求开始计时");

        HttpResponse response = HttpRequest.post(aiServiceURL)
                .header(Header.CONTENT_TYPE, "application/json")
                .body(originImage)
                .timeout(10 * 1000)
                .execute();

        String result = response.body();

        // 解析响应体
        ObjectMapper mapper = new ObjectMapper();
        List<DetectVo> rawList = mapper.readValue(
                response.body(),
                new TypeReference<List<DetectVo>>() {}
        );
        // 转换为按name分类的Map
        Map<String, DetectVo> resultMap = rawList.stream()
                .collect(Collectors.toMap(DetectVo::getName, Function.identity()));

        // 转换为List并保持顺序
        List<DetectVo> detectVoList = new ArrayList<>();
        DetectVo detectVo = resultMap.get("detect");
        detectVoList.add(detectVo);  // 确保detect在前
        detectVoList.add(resultMap.get("segment")); // segment在后

        // 上传检测图片到OSS
        if (detectVo != null && detectVo.getImage() != null) {
            try {
                // 1. 清理base64字符串并转为临时文件
                String base64Image = detectVo.getImage().split(",")[1]; // 去除前缀
                byte[] imageBytes = Base64.getDecoder().decode(base64Image);
                Path tempFile = Files.createTempFile("detepct-", ".jpg");
                Files.write(tempFile, imageBytes);

                // 2. 上传到OSS
                String objectKey = ossUploaderService.uploadToOss(tempFile.toFile(),detectDirectory);

                // 3. 计算成熟度并存储到数据库
                int mature = detectVo.getMature();
                int semiMature = detectVo.getSemi_mature();
                int immature = detectVo.getImmature();
                int total = mature + semiMature + immature;
                double ripeness = total > 0 ? (double)mature / total * 100 : 0;

                History history = History.builder()
                        .objectKey(objectKey)
                        .detectTime(DateTime.now())
                        .userId(ContextHolder.getUserId())
                        .ripeness(ripeness)
                        .ipAddress(request.getRemoteAddr())
                        .build();
                historyMapper.insert(history);

                // 4. 生成访问URL并设置到返回结果
                String imageUrl = ossUploaderService.generatePresignedUrl(objectKey);
                detectVo.setImage(imageUrl);

                // 5. 删除临时文件
                Files.deleteIfExists(tempFile);
            } catch (IOException e) {
                log.error("图片上传处理失败", e);
            }
        }

        //结束计时
        long s2 = System.currentTimeMillis();
        long t = s2 - s1;
        log.info("本次AI请求耗时：{}", t);

        return Result.success(detectVoList);
    }
}
